/*
 * Created on 2004-9-24
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dcivision.workflow.applet.editor;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
* CalendarControl Class 
*/
public class CalendarControl extends Panel implements ActionListener, MouseMotionListener, MouseListener
{
  final private String TITLES[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
  final private int ROW_HEIGHT = 20;
  final private int ROW_WIDTH = 40;
  
  private JTable table; // Table
  private JLabel title; // Title
  private JButton nextMonth; // Next Monthly Button
  private JButton preMonth; // Prev Monthly Button
  private JPanel top; // Top Container
  private JTextField jTFDate;
  
  private int year; // current year
  private int month; // current month
  private int day; // current day
  private int week; // currenty week
  private int selectedX = -1;
  private int selectedY = -1;
  private int clickX = -1;
  private int clickY = -1;
  private int thisday;
  private int thismonth;
  private int thisyear;
  private JDialog jDialog;


  /**
  *
  */
  public CalendarControl()
  {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    
    year = cal.get(Calendar.YEAR);
    month = cal.get(Calendar.MONTH)+1;
    day = cal.get(Calendar.DAY_OF_MONTH)-1;
    thisday = day;
    thismonth = month;
    thisyear = year;
    week = cal.get(Calendar.DAY_OF_WEEK)-1;
    
    top = new JPanel(new FlowLayout(FlowLayout.CENTER));
    table = new JTable(7,7);
    
    table.setPreferredSize(new Dimension(ROW_WIDTH * 7, ROW_HEIGHT * 7));
    table.setRowHeight(ROW_HEIGHT);
    for(int i=0; i<TITLES.length; i++)
    table.setValueAt(TITLES[i],0,i);
    
    title = new JLabel();
    nextMonth = new JButton(">>");
    preMonth = new JButton("<<");
    top.add(preMonth);
    top.add(title);
    top.add(nextMonth);
    setTitle();
    table.setEnabled(false);
    // set button
    setLayout(new BorderLayout());
    
    add(top, BorderLayout.NORTH);
    add(table, BorderLayout.CENTER);
    
    preMonth.addActionListener(this);
    nextMonth.addActionListener(this);
    
    showMonth(); // set display currrent month
    table.setCellSelectionEnabled(true);
    
    table.addMouseMotionListener(this);
    table.addMouseListener(this);
  }
  
  public CalendarControl(JDialog jDialog){
    this();
    this.jDialog = jDialog;
  }
  
  public JTextField getJTFDate(){
    return this.jTFDate;
  }
  
  public void setJTFDate(JTextField jTFDate){
    this.jTFDate = jTFDate;
  }
  
    
    /**
    * get appoint Days by year and month
    * @return
    */
    public int getDaysOfMonth(int year, int month){
      int Days[]= {31,28,31,30,31,30,31,31,30,31,30,31};
      // if this year is 
      
      if( year % 400 == 0 || (year % 4 ==0 && year % 100 != 0)) // leap year
          Days[1] = 29;
      
      return Days[month-1];
    }
    
    /**
    * get the month first day of week
    * @param month
    * @return
    */
    public int getWeekOfFirstDay(int year, int month)
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        
        int result = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return result ;
    }
    
    /**
    * set title
    */
    private void setTitle()
    {
        String m = String.valueOf(month);
        if(m.length() ==1) m = "0"+m;
            title.setText(String.valueOf(year)+" "+m);  
    }
    
    /**
    * show month
    */
    private void showMonth()
    {
        for(int x=0; x<7; x++)
        for(int y=1; y<7; y++) table.setValueAt("",y, x);
        
        int y = 1;
        int x = getWeekOfFirstDay(year, month);
        int maxDay = getDaysOfMonth(year,month);
        
        for(int i=0; i<maxDay; i++)
        {
            table.setValueAt(new Integer(i+1),y,x);
        
            x ++;
            if(x>6)
            {
                x=0;
                y++;
            }
        }
        repaint();
    }
    
    /**
    * button action
    * @param e
    */
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource().equals(nextMonth))
        {
            month++;
            if(month>12)
            {
                month = 1;
                year++;
            }
        }
        
        if(e.getSource().equals(preMonth))
        {
            month--;
            if(month<1)
            {
                month = 12;
                year --;
            }
        }
        
        setTitle();
        showMonth();
    }
    
    /**
    * paint
    * @param g
    */
    public void paint(Graphics g)
    {
        super.paint(g);
        
        // repaint Table First LINE
        g.fillRect(0,top.getHeight(), getWidth()-1, ROW_HEIGHT -1);
        g.setColor(Color.white);
        for(int i=0; i<7; i++)
            g.drawString((String)(table.getModel().getValueAt(0,i)),i*ROW_WIDTH, top.getHeight()+ ROW_HEIGHT - 3);
        
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, thisday);
        int line = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
        int x = week * table.getWidth() / 7;
        int y = top.getHeight() + ROW_HEIGHT * line ;
        
        if(year==thisyear&&month==thismonth){
          g.setColor(Color.black);
          g.drawRect(x+1,y+1, ROW_WIDTH-4, ROW_HEIGHT-4);
        }
        if(selectedX >= 0 && selectedY>= 0 && ! table.getModel().getValueAt(selectedY,selectedX).equals(""))
        {
            g.setColor(Color.blue);
            g.drawRect(selectedX * ROW_WIDTH+1, (selectedY + 2) * ROW_HEIGHT -1 ,ROW_WIDTH-4,ROW_HEIGHT-4);
        }
        
        if(clickY >= 0 && clickX >= 0 & ! table.getModel().getValueAt(clickY,clickX).equals(""))
        {
            g.setColor(Color.red);
            g.drawRect(clickX * ROW_WIDTH+1, (clickY + 2) * ROW_HEIGHT -1 ,ROW_WIDTH-4,ROW_HEIGHT-4);           
        }
    }
    
    public void mouseDragged(MouseEvent e){}
    
    public void mouseMoved(MouseEvent e)
    {
        if(e.getX()>0 && e.getY()<getWidth() && e.getY()> ROW_HEIGHT && e.getY()< ROW_HEIGHT * 7 )
        {
            selectedX = e.getX() / ROW_WIDTH;
            selectedY = e.getY() / ROW_HEIGHT;
            
            //repaint();
        }
    }
    
    public void mouseClicked(MouseEvent e) {
      day = Integer.parseInt(table.getModel().getValueAt(clickY,clickX).toString());
      jTFDate.setText(year+"-"+month+"-"+day);
      jDialog.dispose();
      //this.dispose();
      //System.out.println(year+" "+month+" "+day);
    }
    
    public void mousePressed(MouseEvent e){
        if(e.getX()>0 && e.getY()<getWidth() && e.getY()> ROW_HEIGHT && e.getY()< ROW_HEIGHT * 7 )
        {
            clickX = e.getX() / ROW_WIDTH;
            clickY = e.getY() / ROW_HEIGHT;
        
            repaint();
        }
    }
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    
    /* --=[ test code ]=-- */
    public static void main(String[] args)
    {
      JDialog frm = new JDialog();
        
        frm.getContentPane().setLayout(new BorderLayout());
        frm.getContentPane().add(new CalendarControl(frm));
        //CalendarControl calendarControl = new CalendarControl();
        //calendarControl.pack();
        //calendarControl.show();
        //frm.getContentPane().add(calendarControl, BorderLayout.CENTER);
        //JButton button = new JButton("ok");
        //frm.getContentPane().add(button, BorderLayout.SOUTH);
        //button.addActionListener(new ActionListener(){
            //public void actionPerformed(ActionEvent e){
                //JOptionPane.showConfirmDialog(null,new CalendarControl());
                //System.out.println(s);
                //String s =(String)JOptionPane.showInputDialog( ,"","","",null);
            //}    
        //}
                
        //);
                
                
                
        frm.pack();
        frm.show();
    }
}
